import DeviceInfo from 'react-native-device-info';
import Dictionary from '../utils/dictionary';
import { ENVIRONMENT } from '../config/env';
import { GLOBAL } from '../config/global'

/*
	1. 断网环境(弱网)
	2. 应用在后台时(这时候接收不到消息,要重新发消息)	


*/

//DICTIONARY 数据字典  返回的数据格式为 {"dictDetailList":[{"dictKey":"1","dictName":"一口价","dictTypeCode":"EC_PRICE_TYPE","showIndex":1}],"dictTypeCode":"EC_PRICE_TYPE","type":"DICTIONARY"}

let DeviceID = DeviceInfo.getUniqueID();
let WS = {
    wsObj: null,
    lockReconnect: false,////避免多次连接
    wsCreateHandler: null,
    time: null,
    reconnectTime: 5000, //多久重连
    createWebSocket: function () {
        try {
            if (!GLOBAL.TOKEN) {  // 没有登入 不能长链接
                this.wsCreateHandler && clearTimeout(this.wsCreateHandler);
                return;
            }
            if (this.wsObj) return;
            console.log("this.wsObj-000000", `${ENVIRONMENT[GLOBAL.CURR_ENV].websocket}/${DeviceID}?token=${GLOBAL.TOKEN}`)
            this.wsObj = new WebSocket(`${ENVIRONMENT[GLOBAL.CURR_ENV].websocket}/${DeviceID}?token=${GLOBAL.TOKEN}`);
            console.log("this.wsObj", this.wsObj)
            this.wsObj.onopen = (ev) => {
                console.log("连接成功")
                this.wsObj.send(`{"id":"${DeviceID}","type":"DICTIONARY","data":"连接成功"}`);
            }
            this.wsObj.onmessage = async (ev) => {
                let localTime = await Dictionary.get('vesionId'); // 获取本地版本
                try {
                    let messageData = JSON.parse(ev.data) || {};
                    console.log("客户端接收到消息", messageData);
					/*if (messageData.type === "PING") {
						clearInterval(this.time);
						this.time = setInterval(() => {
							console.log("过5秒,我要重连")
							this.reconnect();
						}, 5000)
					} else if (messageData.type === "DICTIONARY") {
						console.log("我要更新数据字典")
					}*/
                    // 处理页面逻辑
                    if (messageData.type === "DICTIONARY") {
                        if (messageData.vesionId > localTime) {
                            console.log("我要更新数据字典");
                            Dictionary.updated();
                        }
                    }
                } catch (err) {
                    console.log("err", err)
                }
            }
            this.wsObj.onclose = (ev) => {
                //console.log("onclose", this.wsObj)
                this.wsObj = null;
                this.reconnect();
            }
            this.wsObj.onerror = (ev) => {
                //	console.log("onerror");
                this.wsObj = null;
                this.reconnect();
            }
        } catch (e) {
            //console.log("创建异常", e);
            this.reconnect();
        }
    },
    reconnect: function () {
        if (this.lockReconnect || GLOBAL.APP_STATE === "background") return;
        console.log("进入-2秒后重连");
        this.lockReconnect = true;
        this.wsCreateHandler && clearTimeout(this.wsCreateHandler);
        this.wsCreateHandler = setTimeout(() => {
            console.log("重连开始");
            this.createWebSocket();
            this.lockReconnect = false;
            console.log("重连完成");
        }, this.reconnectTime)
    }
}

export default WS;